package org.kl.bf.utils;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.Selection;

import org.springside.modules.utils.Collections3;

import com.google.common.collect.Lists;

/**
 * @author QJ
 * @date 2014年9月11日
 * 动态创建footer
 */
public class KLDynamicFooter {

	@SuppressWarnings("rawtypes")
	public static <T> Selection[] buildSelections(
			final Collection<KLFooterFilter> footerFilters, Root<T> root,
			CriteriaBuilder builder) {
		if (Collections3.isNotEmpty(footerFilters)) {
			List<Selection> selectionList = Lists.newArrayList();
			for (KLFooterFilter filter : footerFilters) {
				selectionList.add(oneSelection(filter, root, builder));
			}
			if (selectionList.size() > 0) {
				return selectionList
						.toArray(new Selection[selectionList.size()]);
			}
		}
		return null;
	}

	@SuppressWarnings("rawtypes")
	private static <T> Selection oneSelection(KLFooterFilter filter,
			Root<T> root, CriteriaBuilder builder) {
		Selection selection = null;
		switch (filter.operator) {
		case SUM:
			selection = builder.sum(root.<BigDecimal> get(filter.fieldName))
					.as(BigDecimal.class).alias(filter.value);
			break;
		case AVG:
			selection = builder.avg(root.<BigDecimal> get(filter.fieldName))
					.as(BigDecimal.class).alias(filter.value);
			break;
		case CNT:
			selection = builder.count(root.<BigDecimal> get(filter.fieldName))
					.as(BigDecimal.class).alias(filter.value);
			break;
		case MAX:
			selection = builder.max(root.<BigDecimal> get(filter.fieldName))
					.as(BigDecimal.class).alias(filter.value);
			break;
		case MIN:
			selection = builder.min(root.<BigDecimal> get(filter.fieldName))
					.as(BigDecimal.class).alias(filter.value);
			break;
		}
		return selection;
	}
}